package com.glodon.paas.consumer.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * @author: Don Li
 */
@Controller
@RequestMapping("/callback")
public class OAuthCallbackController{

//    @Value("${api.host}")
//    private String apiHost;
    
	@RequestMapping(value="", method = RequestMethod.GET)
    public ModelAndView callback(HttpServletRequest request, HttpServletResponse response, ModelMap model){
    	
		String requestToken = request.getParameter("oauth_token");
		if (requestToken == null || "".equals(requestToken)) {
			model.addAttribute("info","authorization is denied");
		}
//		request.setAttribute("oauth_token", requestToken);
//		request.getSession().setAttribute("oauth_token", requestToken);
		
		OAuthProvider provider = (OAuthProvider) request.getSession().getAttribute( "provider");
		OAuthConsumer consumer = (OAuthConsumer) request.getSession().getAttribute( "consumer");

		try {
			// retrieve access token
			provider.retrieveAccessToken(consumer, null);
			model.addAttribute("info","<b>Consumer Key:</b> " + consumer.getConsumerKey()
					+ "<br>");
			model.addAttribute("info","<b>Consumer Secret: </b>"
					+ consumer.getConsumerSecret() + "<br>");
			model.addAttribute("info","<b>Access Token:</b> " + consumer.getToken() + "<br>");
			model.addAttribute("info","<b>Token Secret: </b>" + consumer.getTokenSecret()
					+ "<br>");
			request.getSession().setAttribute("oauth_token", consumer.getToken());
//			model.addAttribute("info","<a href=http://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/APITest.jsp?oauth_token="+requestuestToken+">Test API</a>");
		} catch (Exception e) {
			// not authorized
			model.addAttribute("info","Fail to retrieve access token");
		}
		return new ModelAndView(new RedirectView("api/system"));
	}
}
